var express = require('express');
var router = express.Router();
var db = require('../libs/mysql.js');
//统一返回格式
var res_Data;
router.use( function(req, res, next) {
    res_Data = {
        code: 0,
        message: ''
    }
    next();
});
//用户列表
router.get('/',function (req,res) {// /api
    db.query(`SELECT * FROM user`,(err,data)=>{
        if(err){
            res.send('列表').end();
        }else {
            res.json(data);
        }
    })
})
//登录
router.post('/log',function (req,res) {// /api
    console.log(req.body.log)
    var user = req.body.log.user,
        password = req.body.log.password;

    db.query(`select * from user where user='${user}' and pass='${password}'`,(err,data)=>{
        if(err){
            res.send('登录sql错误').end();
        }else {
            if(data.length == 0){
                res_Data.code = 1;
                res_Data.message = '用户名或密码错误';
                res.json(res_Data);
                return;
            }else {
                res_Data.message = '登录成功';
                res.json(res_Data);
                return;
            }
        }
    })

})

//注册
router.post('/reg',function (req,res) {
    var user = req.body.reg.user,
        password = req.body.reg.password,
        repassword = req.body.reg.repassword;

    if(password != repassword){
        res_Data.code = 1;
        res_Data.message = '密码2次输入不相同。';
        res.json(res_Data);
        return;
    }
    db.query(`INSERT INTO user ( user, pass )
                       VALUES
                       ( '${user}','${password}' );`,(err,data)=>{
        if(err){
            res.send('注册数据插入数据库失败').end();
        }else {
            res_Data.message = '注册成功';
            res.json(res_Data);
            return;
        }
    })


})
module.exports = router;